package com.fstart.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fstart.common.Result;
import com.fstart.common.Utils;
import com.fstart.sys.entity.EmailCode;
import com.fstart.sys.entity.User;
import com.fstart.sys.mapper.UserMapper;
import com.fstart.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xibing
 * @since 2023-04-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private EmailCodeServiceImpl emailCodeService;

    @Autowired
    private JavaMailSender javaMailSender;


    @Value("${FStart.UserTopPath}")
    private String basePath;


    @Override
    public Map<String, Object> login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(User::getUsername, user.getUsername());

        User loginUser = this.baseMapper.selectOne(wrapper);

        if (loginUser != null && passwordEncoder.matches(user.getPassword(), loginUser.getPassword())) {
            // 登录成功
            // 生成token，暂时用UUID，终极方案是jwt
            String key = "user:" + UUID.randomUUID();
            // 存入redis
            // 存入redis
            loginUser.setPassword(null);
//            redisTemplate.opsForValue().set(key, loginUser,30, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(key, loginUser, 24 * 60, TimeUnit.MINUTES);

            // 返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", key);
            return data;
        }

        // 登录失败
        return null;
    }

    @Override
    public Map<String, Object> getUserinfo(String token) {
        // 查询redis中的用户信息
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj != null) {
            // 将数据转成json数据
            User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);

            Map<String, Object> data = new HashMap<>();
            data.put("userId", loginUser.getId());
            data.put("name", loginUser.getUsername());
            data.put("avatar", loginUser.getAvatar());
            data.put("email", loginUser.getEmail());

            return data;
        }
        return null;
    }

    @Override
    public void logout(String token) {
        // 删除redis中的用户信息
        redisTemplate.delete(token);
    }

    @Override
    public User updateUserTop(User user, String token) {



        Object obj = redisTemplate.opsForValue().get(token);

        if (obj != null) {
            // 将数据转成json数据
            User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);

            // 删除原来的头像
//            String fileName = loginUser.getAvatar().split("=")[1];
//            File file = new File(basePath+fileName);
//            if (file.exists()){
//                file.delete();
//            }

            loginUser.setAvatar(user.getAvatar());


            // 修改redis中的数据
            redisTemplate.opsForValue().set(token, loginUser);

            return loginUser;

        }

        return null;

    }

    @Override
    public boolean sendEmailCode(Map<String, String> email) {

        // 生成验证码随机
        String EmailCode = Utils.randomStr(6);

        EmailCode emailCode = new EmailCode();
        // 验证码到数据库中
        String uuid = UUID.randomUUID().toString();
        emailCode.setId(uuid);
        emailCode.setEmail(email.get("email"));
        emailCode.setCode(EmailCode);

        emailCode.setStatus("0");
        emailCode.setCreateTime(LocalDateTime.now());

        // 发送验证码
        boolean sendFlag = Utils.sendEmailCode(EmailCode, "898670865@qq.com", email.get("email"), javaMailSender, email.get("message"));

        if(sendFlag){
            emailCodeService.save(emailCode);
        }

        return sendFlag;

    }


}
